/**
 * 维护登录状态
 */
import { initCache } from '@/models';
import deviceListModel from '@/models/deviceList';
import deviceShareModel from '@/models/deviceShare';
import SDKModel from '@/models/gizwitsSdk';
import homesModel from '@/models/homes';
import userStateModel from '@/models/userState';
import walletModel from '@/models/wallet';
import Taro from '@tarojs/taro';
import SecureStore from './AsyncStorage';
import global from './global';
import Toast from './Toast';

const StorageTokenKey = 'token';
const StorageUidKey = 'uid';

// eslint-disable-next-line consistent-return
export async function getToken() {
  try {
    return await SecureStore.getItem(StorageTokenKey);
  } catch (error) {
    console.error(error);
  }
}

export async function setSentryUserInfo() {
  const uid = await SecureStore.getItem(StorageUidKey);
  if (uid) {
    __non_webpack_require__.async('./pages/configDevice/sentry-miniapp.wx.min').then((Sentry) => {
      Sentry.setUser({
        id: uid
      });
    })
  }
}

const StorageWechatUnionidKey = 'wechatUnionidKey';
export { StorageWechatUnionidKey, StorageTokenKey, StorageUidKey }

export async function setTokenInfo({
  token,
  uid,
  createdAt,
  expiredAt,
  refreshToken,
  openid,
  unionid
}: ILoginProps) {
  try {
    global.token = token;
    console.log('setTokenInfo', token);
    await SecureStore.setItem(StorageTokenKey, token);
    if (uid) {
      await SecureStore.setItem(StorageUidKey, uid);
    }
    if (refreshToken) {
      await SecureStore.setItem('refreshToken', refreshToken);
      await SecureStore.setItem('createdAt', `${createdAt}`);
      await SecureStore.setItem('expiredAt', `${expiredAt}`);
    }
    if (openid || unionid) {
      await SecureStore.setItem(StorageWechatUnionidKey, unionid ?? openid ?? '');
    }
    setSentryUserInfo();
  } catch (error) {
    console.error(error);
  }
  return true;
}

/**
 * 保存token之类的操作
 */
export interface ILoginProps {
  token: string;
  uid?: string;
  createdAt?: number;
  expiredAt?: number;
  refreshToken?: string;
  openid?: string;
  unionid?: string;
}
export async function login(data: ILoginProps) {
  console.log('loginloginloginlogin', data)
  await setTokenInfo(data);
  return true;
}

export async function getLoginInfo() {
  try {
    const token = await SecureStore.getItem(StorageTokenKey);
    const uid = await SecureStore.getItem(StorageUidKey);
    return { uid, token };
  } catch (error) {
    console.error(error);
    return {};
  }
}

export function goToLoginPage() {
  // pages/newLogin/index pages/login/home/home
  Taro.navigateTo({ url: `/pages/newLogin/index` });
}

export async function wechatLogin(data: ILoginProps) {
  console.log('wechatLogin', data)
  Toast.loading('');
  await login(data);
  await haveLoginDataInit();
  Toast.hideLoading();
}

async function initMobxCacheData() {
  try {
    const cacheList = [
      'homes',
      'deviceData',
      'deviceList',
    ];
    const cache: any = {};
    for (let i = 0; i < cacheList.length; i++) {
      const key = cacheList[i];
      const data = await SecureStore.getItem(key);
      if (data) {
        cache[key] = data;
      }
    }
    console.log('cache', cache);
    await initCache(cache);
  } catch (error) {
    console.log('initMobxCacheData', error);
  }
}

export async function haveLoginDataInit() {
  await initMobxCacheData();
  await SDKModel.initWithCurrentLanguage();
  await homesModel.initHomes();
  await deviceShareModel.init();
  await deviceListModel.getDeviceList();
  await userStateModel.getUserInfo();
  await deviceShareModel.checkDeviceShare();
  await walletModel.getBalance();
}


export function checkIsLogin(autoGoLoginPage = true) {
  if (global.token) {
    return true;
  }
  if (autoGoLoginPage) {
    goToLoginPage();
  }
  return false;
}

export function getWechatId() {
  return SecureStore.getItem(StorageWechatUnionidKey)
}
